package com.topone.controller;

import com.topone.Enum.ResultEnum;
import com.topone.Enum.TcUserCouponEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dataObject.TcUserCoupon;
import com.topone.dto.BussinessDTO;
import com.topone.dto.CartDTO;
import com.topone.dto.TcUserCouponDTO;
import com.topone.service.TcCouponService;
import com.topone.service.TcUserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/26,0026.
 */
@RequestMapping("/buyer/userCoupon")
@RestController
@Slf4j
@CrossOrigin
public class UserCouponController {
    @Autowired
    private TcUserCouponService tcUserCouponService;

    @Autowired
    private TcCouponService tcCouponService;

    @GetMapping("/list")
    public ResultVO<Map<String,Object>> bussinessCoupon(@RequestParam("openid")
                                                String openid,
                                    @RequestParam("flag") Integer flag,
                                    Map<String, Object> map){
        if(StringUtils.isEmpty(openid)){
            log.error("openid为空");
            return ResultVOUntil.error(1,"openid为空");
        }
        else if(StringUtils.isEmpty(flag)){
            log.error("flag为空");
            return ResultVOUntil.error(1,"flag为空");
        }
        try {
            TcUserCoupon tcUserCoupon=new TcUserCoupon();
            tcUserCoupon.setBuyerOpenid(openid);
            tcUserCoupon.setUseStatus(flag);
            List<BussinessDTO> userCouponList= tcUserCouponService.findCouponByopenid(tcUserCoupon);
            map.put("userCouponList",userCouponList);
        }catch (FanZoneException e){
            log.error("【查询用户优惠券】失败，e={}",e);
            map.put("error",e.getMessage());
            return ResultVOUntil.error(1,e.getMessage());
        }
        log.info("【查询用户优惠券】成功 {}",map);
        return ResultVOUntil.success(map);
    }

    @GetMapping("/dealOvertimeUnpayUserCoupon")
    @Transactional
    public  ResultVO<Map<String,Object>> dealUnpayUserCoupon(Map<String,Object> map){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = simpleDateFormat.format(new Date());
            log.info("【更新未支付状态】开始处理",nowTime);
            long from =simpleDateFormat.parse(nowTime).getTime();
            CartDTO cartDTO=new CartDTO();
            List<TcUserCouponDTO> tcUserCouponDTOList = new ArrayList<>();
            try {
                tcUserCouponDTOList = tcUserCouponService.findAllUserCoupon(TcUserCouponEnum.UNPAY.getCode());
            } catch (Exception e) {
                throw new FanZoneException(ResultEnum.SCHEDULETASK_ERROR);
            }
            if (tcUserCouponDTOList != null && tcUserCouponDTOList.size() > 0) {
                for (int i = 0; i < tcUserCouponDTOList.size(); i++) {
                    TcUserCouponDTO tcUserCouponDTO=tcUserCouponDTOList.get(i);
                    //获取用户优惠券生成时间
                    String effectiveTime=simpleDateFormat
                            .format(tcUserCouponDTO.getCreateTime());
                    long to=simpleDateFormat.parse(effectiveTime).getTime();
                    long days =((from - to)/(1000 * 60 * 60 * 24));
                    //如果用户订单超过一天未支付自动取消
                    if(days>1){
                        try {
                            //更新tc_user_coupon状态
                            tcUserCouponService.cancelUserCoupon(tcUserCouponDTO.getId());
                            log.info("【更新未支付状态】用户优惠券状态更新成功,tc_user_coupon={}",tcUserCouponDTO);
                            List<CartDTO> cartDTOList=new ArrayList<>();
                            cartDTO.setCouponId(tcUserCouponDTO.getCouponId());
                            cartDTO.setCouponQuanlity(tcUserCouponDTO.getCouponNum());
                            cartDTOList.add(cartDTO);
                            //退还库存
                            tcCouponService.increaseStock(cartDTOList);
                            log.info("【更新未支付状态】退还库存成功，{}",cartDTOList);
                        }catch (Exception e){
                            throw new FanZoneException(ResultEnum.UPDATE_USERCOUPON_ERROR);
                        }
                    }else{
                        //一旦找到一天以内的未支付的订单，接下来的所有订单都在有效期内，sql顺序查询出来的数据
                        // 那将不作处理
                        break;
                    }
                }
            }
            log.info("【处理用户超时未支付的订单】处理结束",simpleDateFormat.format(new Date()));
        }catch (Exception e){
            log.error("【处理用户超时未支付的订单】失败,{}",e.getMessage());
            e.printStackTrace();
            return ResultVOUntil.error(1,e.getMessage());
        }
        log.info("【处理用户超时未支付的订单】成功,{}",map);
        return ResultVOUntil.success();
    }

    @GetMapping("/dealUserCouponOverTime")
    public ResultVO<Map<String,Object>> dealUserCouponOverTime(Map<String,Object> map){
        List<TcUserCouponDTO> tcUserCouponDTOList=new ArrayList<>();
        try {
            tcUserCouponDTOList= tcUserCouponService
                    .findUserCouponOvertime(TcUserCouponEnum.UNUSE.getCode());
            map.put("success",tcUserCouponDTOList.size());
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        log.info("处理用户超时未使用优惠券成功,{}",tcUserCouponDTOList);
        return ResultVOUntil.success(map);
    }
}
